package com.datagateway.controller;

import com.datagateway.component.DataStatisticsManager;
import com.datagateway.component.ReportGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.CompletableFuture;

/**
 * 数据统计控制器
 * 提供数据统计和报表生成相关的REST API接口
 * 
 * @author Data Gateway Team
 * @version 1.0.0
 */
@RestController
@RequestMapping("/data-gateway/api/statistics")
public class DataStatisticsController {

    @Autowired
    private DataStatisticsManager dataStatisticsManager;

    @Autowired
    private ReportGenerator reportGenerator;

    /**
     * 获取系统统计信息
     * 
     * @return 系统统计信息
     */
    @GetMapping("/system")
    public Map<String, Object> getSystemStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataStatisticsManager.SystemStatistics stats = dataStatisticsManager.getSystemStatistics();
            
            result.put("success", true);
            result.put("statistics", stats);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取系统统计信息异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取时间窗口统计
     * 
     * @param timeWindow 时间窗口（分钟）
     * @return 时间窗口统计
     */
    @GetMapping("/time-window")
    public Map<String, Object> getTimeWindowStatistics(@RequestParam(defaultValue = "60") int timeWindow) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<DataStatisticsManager.TimeWindowStatistics> stats = 
                dataStatisticsManager.getTimeWindowStatistics(timeWindow);
            
            result.put("success", true);
            result.put("statistics", stats);
            result.put("count", stats.size());
            result.put("timeWindow", timeWindow);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取时间窗口统计异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取业务统计
     * 
     * @return 业务统计列表
     */
    @GetMapping("/business")
    public Map<String, Object> getBusinessStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<DataStatisticsManager.BusinessStatistics> stats = 
                dataStatisticsManager.getBusinessStatistics();
            
            result.put("success", true);
            result.put("statistics", stats);
            result.put("count", stats.size());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取业务统计异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取性能统计
     * 
     * @return 性能统计
     */
    @GetMapping("/performance")
    public Map<String, Object> getPerformanceStatistics() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataStatisticsManager.PerformanceStatistics stats = 
                dataStatisticsManager.getPerformanceStatistics();
            
            result.put("success", true);
            result.put("statistics", stats);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取性能统计异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成日报表
     * 
     * @param date 日期（格式：yyyy-MM-dd）
     * @param format 报表格式（HTML、JSON、CSV、TXT）
     * @return 报表生成结果
     */
    @PostMapping("/reports/daily")
    public Map<String, Object> generateDailyReport(@RequestParam String date, 
                                                  @RequestParam(defaultValue = "HTML") String format) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Date reportDate = new java.text.SimpleDateFormat("yyyy-MM-dd").parse(date);
            CompletableFuture<String> future = reportGenerator.generateDailyReport(reportDate, format);
            
            result.put("success", true);
            result.put("message", "日报表生成任务已提交");
            result.put("date", date);
            result.put("format", format);
            result.put("future", future);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成日报表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成周报表
     * 
     * @param weekStartDate 周开始日期（格式：yyyy-MM-dd）
     * @param format 报表格式（HTML、JSON、CSV、TXT）
     * @return 报表生成结果
     */
    @PostMapping("/reports/weekly")
    public Map<String, Object> generateWeeklyReport(@RequestParam String weekStartDate, 
                                                   @RequestParam(defaultValue = "HTML") String format) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Date reportDate = new java.text.SimpleDateFormat("yyyy-MM-dd").parse(weekStartDate);
            CompletableFuture<String> future = reportGenerator.generateWeeklyReport(reportDate, format);
            
            result.put("success", true);
            result.put("message", "周报表生成任务已提交");
            result.put("weekStartDate", weekStartDate);
            result.put("format", format);
            result.put("future", future);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成周报表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成月报表
     * 
     * @param month 月份（格式：yyyy-MM）
     * @param format 报表格式（HTML、JSON、CSV、TXT）
     * @return 报表生成结果
     */
    @PostMapping("/reports/monthly")
    public Map<String, Object> generateMonthlyReport(@RequestParam String month, 
                                                    @RequestParam(defaultValue = "HTML") String format) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Date reportDate = new java.text.SimpleDateFormat("yyyy-MM").parse(month);
            CompletableFuture<String> future = reportGenerator.generateMonthlyReport(reportDate, format);
            
            result.put("success", true);
            result.put("message", "月报表生成任务已提交");
            result.put("month", month);
            result.put("format", format);
            result.put("future", future);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成月报表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成系统统计报表
     * 
     * @param format 报表格式（HTML、JSON、CSV、TXT）
     * @return 报表生成结果
     */
    @PostMapping("/reports/system")
    public Map<String, Object> generateSystemReport(@RequestParam(defaultValue = "HTML") String format) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            CompletableFuture<String> future = reportGenerator.generateSystemReport(format);
            
            result.put("success", true);
            result.put("message", "系统统计报表生成任务已提交");
            result.put("format", format);
            result.put("future", future);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成系统统计报表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成业务统计报表
     * 
     * @param format 报表格式（HTML、JSON、CSV、TXT）
     * @return 报表生成结果
     */
    @PostMapping("/reports/business")
    public Map<String, Object> generateBusinessReport(@RequestParam(defaultValue = "HTML") String format) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            CompletableFuture<String> future = reportGenerator.generateBusinessReport(format);
            
            result.put("success", true);
            result.put("message", "业务统计报表生成任务已提交");
            result.put("format", format);
            result.put("future", future);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成业务统计报表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成性能统计报表
     * 
     * @param format 报表格式（HTML、JSON、CSV、TXT）
     * @return 报表生成结果
     */
    @PostMapping("/reports/performance")
    public Map<String, Object> generatePerformanceReport(@RequestParam(defaultValue = "HTML") String format) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            CompletableFuture<String> future = reportGenerator.generatePerformanceReport(format);
            
            result.put("success", true);
            result.put("message", "性能统计报表生成任务已提交");
            result.put("format", format);
            result.put("future", future);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成性能统计报表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成时间窗口统计报表
     * 
     * @param timeWindow 时间窗口（分钟）
     * @param format 报表格式（HTML、JSON、CSV、TXT）
     * @return 报表生成结果
     */
    @PostMapping("/reports/time-window")
    public Map<String, Object> generateTimeWindowReport(@RequestParam(defaultValue = "60") int timeWindow,
                                                       @RequestParam(defaultValue = "HTML") String format) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            CompletableFuture<String> future = reportGenerator.generateTimeWindowReport(timeWindow, format);
            
            result.put("success", true);
            result.put("message", "时间窗口统计报表生成任务已提交");
            result.put("timeWindow", timeWindow);
            result.put("format", format);
            result.put("future", future);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成时间窗口统计报表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 生成综合报表
     * 
     * @param format 报表格式（HTML、JSON、CSV、TXT）
     * @return 报表生成结果
     */
    @PostMapping("/reports/comprehensive")
    public Map<String, Object> generateComprehensiveReport(@RequestParam(defaultValue = "HTML") String format) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            CompletableFuture<String> future = reportGenerator.generateComprehensiveReport(format);
            
            result.put("success", true);
            result.put("message", "综合报表生成任务已提交");
            result.put("format", format);
            result.put("future", future);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "生成综合报表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取报表列表
     * 
     * @return 报表文件列表
     */
    @GetMapping("/reports")
    public Map<String, Object> getReportList() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            List<ReportGenerator.ReportFile> reports = reportGenerator.getReportList();
            
            result.put("success", true);
            result.put("reports", reports);
            result.put("count", reports.size());
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取报表列表异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 删除报表文件
     * 
     * @param fileName 文件名
     * @return 删除结果
     */
    @DeleteMapping("/reports/{fileName}")
    public Map<String, Object> deleteReport(@PathVariable String fileName) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            boolean success = reportGenerator.deleteReport(fileName);
            
            result.put("success", success);
            result.put("message", success ? "报表文件删除成功" : "报表文件删除失败");
            result.put("fileName", fileName);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除报表文件异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取统计配置
     * 
     * @return 统计配置
     */
    @GetMapping("/config")
    public Map<String, Object> getStatisticsConfiguration() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataStatisticsManager.StatisticsConfiguration config = dataStatisticsManager.getConfiguration();
            
            result.put("success", true);
            result.put("configuration", config);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取统计配置异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 设置统计配置
     * 
     * @param request 配置请求
     * @return 设置结果
     */
    @PostMapping("/config")
    public Map<String, Object> setStatisticsConfiguration(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            Boolean enabled = (Boolean) request.get("enabled");
            Integer timeWindowSize = (Integer) request.get("timeWindowSize");
            Integer maxTimeWindows = (Integer) request.get("maxTimeWindows");
            Integer reportInterval = (Integer) request.get("reportInterval");
            Integer retentionDays = (Integer) request.get("retentionDays");
            
            if (enabled == null || timeWindowSize == null || maxTimeWindows == null || 
                reportInterval == null || retentionDays == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数");
                return result;
            }
            
            dataStatisticsManager.setConfiguration(enabled, timeWindowSize, maxTimeWindows, 
                reportInterval, retentionDays);
            
            result.put("success", true);
            result.put("message", "统计配置设置成功");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置统计配置异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 设置报表生成配置
     * 
     * @param request 配置请求
     * @return 设置结果
     */
    @PostMapping("/reports/config")
    public Map<String, Object> setReportConfiguration(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String outputPath = (String) request.get("outputPath");
            Boolean autoGenerate = (Boolean) request.get("autoGenerate");
            String format = (String) request.get("format");
            String template = (String) request.get("template");
            Boolean includeCharts = (Boolean) request.get("includeCharts");
            String title = (String) request.get("title");
            
            if (outputPath == null || autoGenerate == null || format == null || 
                template == null || includeCharts == null || title == null) {
                result.put("success", false);
                result.put("message", "缺少必要参数");
                return result;
            }
            
            reportGenerator.setConfiguration(outputPath, autoGenerate, format, 
                template, includeCharts, title);
            
            result.put("success", true);
            result.put("message", "报表生成配置设置成功");
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "设置报表生成配置异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 记录测试数据
     * 
     * @param request 测试数据请求
     * @return 记录结果
     */
    @PostMapping("/test-data")
    public Map<String, Object> recordTestData(@RequestBody Map<String, Object> request) {
        Map<String, Object> result = new HashMap<>();
        
        try {
            String messageId = (String) request.getOrDefault("messageId", UUID.randomUUID().toString());
            Boolean success = (Boolean) request.getOrDefault("success", true);
            Long dataSize = ((Number) request.getOrDefault("dataSize", 1024)).longValue();
            Long processingTime = ((Number) request.getOrDefault("processingTime", 100)).longValue();
            String businessType = (String) request.getOrDefault("businessType", "test");
            Integer retryCount = (Integer) request.getOrDefault("retryCount", 0);
            
            dataStatisticsManager.recordMessageProcessing(messageId, success, dataSize, 
                processingTime, businessType, retryCount);
            
            result.put("success", true);
            result.put("message", "测试数据记录成功");
            result.put("messageId", messageId);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "记录测试数据异常: " + e.getMessage());
        }
        
        return result;
    }

    /**
     * 获取统计概览
     * 
     * @return 统计概览
     */
    @GetMapping("/overview")
    public Map<String, Object> getStatisticsOverview() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            DataStatisticsManager.SystemStatistics systemStats = dataStatisticsManager.getSystemStatistics();
            List<DataStatisticsManager.BusinessStatistics> businessStats = dataStatisticsManager.getBusinessStatistics();
            DataStatisticsManager.PerformanceStatistics performanceStats = dataStatisticsManager.getPerformanceStatistics();
            List<ReportGenerator.ReportFile> reports = reportGenerator.getReportList();
            
            Map<String, Object> overview = new HashMap<>();
            overview.put("system", systemStats);
            overview.put("business", businessStats);
            overview.put("performance", performanceStats);
            overview.put("reports", reports);
            overview.put("timestamp", System.currentTimeMillis());
            
            result.put("success", true);
            result.put("overview", overview);
            
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取统计概览异常: " + e.getMessage());
        }
        
        return result;
    }
}
